#include <wx/datetime.h>
#include <wx/intl.h>
#include "ThreadSearchTrace.h"

ThreadSearchTrace* ThreadSearchTrace::ms_Tracer = NULL;

bool ThreadSearchTrace::Trace( const wxString& str ) {
  wxASSERT( ms_Tracer != NULL );
  wxMutexLocker mutexLocker( *ms_Tracer );
  if( mutexLocker.IsOk() ) {
    if( ( ms_Tracer != NULL ) && ( ms_Tracer->IsOpened() == true ) ) {
      wxDateTime now = wxDateTime::Now();
      ms_Tracer->Write( _T( " " ) + wxString::Format( _T( "%d:%d:%d:%d %s\n" ), now.GetHour(), now.GetMinute(), now.GetSecond(), now.GetMillisecond(), str.c_str() ) );
    }
  }
  return mutexLocker.IsOk();
}

bool ThreadSearchTrace::Init( const wxString& path ) {
  wxASSERT( ms_Tracer == NULL );
  ms_Tracer = new ThreadSearchTrace();
  if( wxFile::Exists( path ) ) {
    wxRemoveFile( path );
  }
  return ms_Tracer->Open( path.c_str(), wxFile::write_excl );
}

void ThreadSearchTrace::Uninit() {
  wxASSERT( ms_Tracer != NULL );
  wxMutexLocker mutexLocker( *ms_Tracer );
  if( mutexLocker.IsOk() ) {
    if( ms_Tracer != NULL ) {
      if( ms_Tracer->IsOpened() == true ) {
        ms_Tracer->Close();
      }
      delete ms_Tracer;
      ms_Tracer = NULL;
    }
  }
}


TraceBeginEndOfMethod::TraceBeginEndOfMethod( const wxString& method )
  : m_Method( method ) {
  wxString begin( _T( "Begin of " ) );
  begin += m_Method;
  ThreadSearchTrace::Trace( begin );
}

TraceBeginEndOfMethod::~TraceBeginEndOfMethod() {
  wxString end( _T( "End of " ) );
  end += m_Method;
  ThreadSearchTrace::Trace( end );
}
